<?php

namespace app\controllers;


use app\models\Admin;
use app\models\Information;
use app\models\RedisCache;
use app\models\TestImg;
use Yii;
use yii\data\Pagination;
use app\models\Customer;
use yii\web\Controller;
use app\controllers\PowerController;
class AdminController extends PowerController
{
    public function init(){
        $this->enableCsrfValidation = false;
    }

    /**
     * @return string
     * 首页
     */
    public function actionIndex()
    {
        $user = new Customer();
        $count = $user->find()->asArray()->all();
        $Due = array();
        $Expired = array();
        for ($i=0;$i<count($count);$i++){
            if ($count[$i]['type']=='1' && $count[$i]['code']=='1'){
                $Due[$i] = $count[$i];
            }elseif ($count[$i]['type']=='0' && $count[$i]['code']=='1'){
                $Expired[$i] = $count[$i];
            }
        }
        $data = [
            'sum' => count($count),
            'due' => count($Due),
            'expired' => count($Expired),
            'hb' => array_merge($Due,$Expired)
            ];
        return $this->render('index',['data'=>$data]);
    }

    public function actionPass(){
        return $this->render('pass');
    }

    /*
     * 生成短链接
     */
    public function actionShort(){
    $req = Yii::$app->request;
    if ($req->isPost){
        $id = $req->post('id');
        $address = $req->post('address');
        $yaddress = $req->post('yaddress');
        $user = Information::findOne(['id'=>$id]);
        $user->Short = $yaddress;
        $user->Shortie = $address;
        if ($user->save()){
            $data = [
                'name'=>$user->alias,
                'address'=>$user->address,
                'Short'=>$user->Short,
                'Shortie'=>$user->Shortie,
                'type'=>$user->type,
                'time'=>$user->time
            ];
            RedisCache::set($user->alias,$data);
            $msg = [
                'code' => 1,
                'msg' => '提交成功'
            ];
        }
        else{
            $msg = [
                'code' => 0,
                'msg' => '提交失败'
            ];
        }
        exit(json_encode($msg));
    }else{
        return $this->render('short');
    }
    }

    public function actionPassword(){
        $req = Yii::$app->request;
        $pass = $req->post('pass',0);
        $pass_two = $req->post('pass_two',0);
        if ($pass!==$pass_two){
            exit(json_encode(['code'=>'0','mag'=>'密码不一致！']));
        }
        if (strlen($pass_two)>8 && strlen($pass)>8){
            exit(json_encode(['code'=>'0','mag'=>'密码长度超过八位！']));
        }
        $user = Admin::findOne(['id'=>1]);
        if ($user->password==md5(md5($pass).$user->pwd_pass)){
            exit(json_encode(['code'=>'0','mag'=>'密码未做修改！']));
        }
        $user->password = md5(md5($pass).$user->pwd_pass);
        if ($user->save()){
            exit(json_encode(['code'=>'1','mag'=>'修改成功！']));
        }else{
            exit(json_encode(['code'=>'1','mag'=>'修改失败！']));
        }
    }

    /**
     * 用户列表
     */
    public function actionUser(){
        $user = new Customer();
        $model = $user->find();
        $pages = new Pagination([
            'totalCount' =>  $model->count(),
            'pageSize' => 20,  // 分页默认条数是20条,但你可以随意设置 例如 5条
        ]);
        $models = $model->offset($pages->offset)
            ->limit($pages->limit)
            ->asArray()
            ->all();
        return $this->render('user',[
            'models' => $models,
            'pages' => $pages,
        ]);
    }

    /*
     * 生成对应用户系统内部链接
     */
    public function actionNewuser(){
        $user = new Information();
        $model = $user->find();
        $pages = new Pagination([
            'totalCount' =>  $model->count(),
            'pageSize' => 20,  // 分页默认条数是20条,但你可以随意设置 例如 5条
        ]);
        $models = $model->offset($pages->offset)
            ->limit($pages->limit)
            ->asArray()
            ->all();
        return $this->render('newuser',[
            'models' => $models,
            'pages' => $pages,
        ]);
    }

    /**
     * 添加用户/更新生成用户信息
     */
    public function actionAdduser(){
        $req = Yii::$app->request;
        if ($req->isGet){
            if($req->get('id')==null){
                $data = [
                    'title' => "添加用户"
                ];
            }else{
                $id = trim(\yii\helpers\Html::encode($req->get('id')));
                $user = new Customer();//实例化用户表
                $list = $user->find()->where(['userid'=>$id])->asArray()->one();
                $test = new TestImg();
                $lists = $test->find()->where(['userid'=>$id])->asArray()->one();
                $data = [
                    'title' => "修改用户",
                    'id' => $list['userid'],
                    'user' =>$list['username'],
                    'time' => $list['due_time'],
                    'img' => $lists['img_address'],
                    'app' => $lists['app_address'],
                    'ios' => $lists['ios_address']
                ];
            }
            return $this->render('adduser',['data'=>$data]);
        }
    }

    public function actionAddUserFrom(){
        //生成用户别名
        $up_code = 'wc'.date('ymdhis');
        //实例化记录表
        $req = Yii::$app->request;
        $db = Yii::$app->db;
        $cache = Yii::$app->cache;
        if ($req->isPost){
            $name = $req->post('user');
            $due_time = $req->post('due_time');
            $address = $req->post('address');
            if (empty($name) || empty($due_time)){
                $msg = [
                    'code' => 0,
                    'msg' => '必填项为空'
                ];
            }
            $url = Yii::$app->params['Url'].'/default/ns?key='.base64_encode($up_code);
            $str = [
                'name'=>$name,
                'alias'=>$up_code,
                'address'=>$address,
                'url'=>$url,
                'type'=>1,
                'time'=>$due_time,
                'startime'=>date('Y-m-d H:i:s')
            ];
            $data = $db->createCommand()->insert('information',$str)->execute();
            //判断用户信息
            if ($data){
                $msg = [
                    'code' => 1,
                    'msg' => '提交成功'
                ];
            }else{
                $msg = [
                    'code' => 0,
                    'msg' => '提交失败'
                ];
            }
            exit(json_encode($msg));
        }
    }

    /**
     * 添加用户/更新用户信息
     */
    public function actionAdd(){
        $req = Yii::$app->request;
        if ($req->isGet){
            if($req->get('id')==null){
                $data = [
                    'title' => "添加用户"
                ];
            }else{
                $id = trim(\yii\helpers\Html::encode($req->get('id')));
                $user = new Customer();//实例化用户表
                $list = $user->find()->where(['userid'=>$id])->asArray()->one();
                $test = new TestImg();
                $lists = $test->find()->where(['userid'=>$id])->asArray()->one();
                $data = [
                    'title' => "修改用户",
                    'id' => $list['userid'],
                    'user' =>$list['username'],
                    'time' => $list['due_time'],
                    'img' => $lists['img_address'],
                    'app' => $lists['app_address'],
                    'ios' => $lists['ios_address']
                ];
            }
            return $this->render('add',['data'=>$data]);
        }
    }

    public function actionAddFrom(){
        $user = new Customer();
        //查询用户中最大的userid编号
        $uid = $user->find()->max('userid');
        $uid+=1;
        $up_code = '';
        $up_user = '';
        //实例化记录表
        $test_img = new TestImg();
        $req = Yii::$app->request;
        if ($req->isPost){
            if (!empty($_FILES)){

                if (!$req->post('id',0)){
                    foreach ($_FILES as $i=>$v){
                        if ($v['type']=='image/png') {
                            $destination = './upload/image/';
                        }else{
                            $destination = './upload/page/';
                        }
                        $filename    = 'good-'.$uid.strrchr($v['name'], ".");
                        $address[$i] = $destination.$filename;
                        move_uploaded_file($v['tmp_name'], $destination . iconv("UTF-8", "gb2312", $filename));
                    }
                    $test_img->upload_time = time();
                    $test_img->userid = $uid;
                    $test_img->img_address = $address['up_img'];
                    $test_img->app_address = $address['up_app'];
                    $test_img->ios_address = $address['up_ios'];
                    if ($test_img->save(false)){
                        $up_code = true;
                    }else{
                        $up_code = false;
                    }
                }else{
                    $userid = $req->post('id');
                    foreach ($_FILES as $i=>$v){
                        if ($v['type']=='image/png') {
                            $destination = './upload/image/';
                        }else{
                            $destination = './upload/page/';
                        }
                        $filename    = 'good-'.$userid.strrchr($v['name'], ".");
                        $address = $destination.$filename;
                        if (file_exists($address)){
                            unlink( $destination.$filename);
                        }
                        move_uploaded_file($v['tmp_name'], $destination . iconv("UTF-8", "gb2312", $filename));
                    }
                        $up_code = true;
                }
            }
            //判断用户信息
            else if ($req->post('user',0) && $req->post('due_time',0)){
                    $user->userid = $uid;
                    $user->username = $req->post('user',0);
                    $user->time = time();
                    $user->password = md5(md5(123456).'520');
                    $user->pwd_pass = '520';
                    $user->type = 1;
                    $user->code = 0;
                    $user->due_time = $req->post('due_time',0);
                    if ($user->save(false)){
                        $up_user = true;
                    }else{
                        $up_user = false;
                    }
            }
            if ($up_user || $up_code){
                $msg = [
                    'code' => 1,
                    'msg' => '提交成功'
                ];
            }else{
                $msg = [
                    'code' => 0,
                    'msg' => '提交失败'
                ];
            }
            exit(json_encode($msg));
        }
    }

    public function actionCan(){
        $req = Yii::$app->request;
        $id = $req->post('id',0);
        if ($id){
            $app =base64_encode("uid=".$id."&type=1");
            $ios =base64_encode("uid=".$id."&type=2");
            $data = [
                'code'=>'1',
                'app'=>Yii::$app->params['Url'].'?key='.$app,
                'ios'=>Yii::$app->params['Url'].'?key='.$ios,
            ];
        }else{
            $data = [
                'code'=>'0'
            ];
        }
        exit(json_encode($data));
    }

    /*
     * 地址展现
     */
    public function actionCanuser(){
        $req = Yii::$app->request;
        $id = $req->post('id',0);
        if ($id){
            $user = Information::find()->where(['id'=>$id])->asArray()->one();
            $data = [
                'code'=>'1',
                'address'=>$user['address'],
                'url'=>$user['url'],
                'Shortie'=>$user['Shortie'],
                'Short'=>$user['Short'],
            ];
        }else{
            $data = [
                'code'=>'0'
            ];
        }
        exit(json_encode($data));
    }

    public function actionSwitchuser(){
        $req = Yii::$app->request;
        $cache = Yii::$app->cache;
        $id = $req->post('id');
        if ($id){
            $user = Information::findOne(['id'=>$id]);
            if (time()<strtotime($user['time'])){
                if ($user->type==1){
                    $type = 0;
                }else if ($user->type==0){
                    $type = 1;
                }
                $user->type = $type;
                $user->save();
                $name = $user->alias;
                if($cache->set($name,$data,3600*23)){
                    $msg = [
                        'code'=>'1',
                        'msg'=>'存储成功'
                    ];
                }else{
                    $msg = [
                        'code'=>'0',
                        'msg'=>'存储失败'
                    ];
                }
            }else{
                $msg = [
                    'code'=>'0',
                    'msg'=>'请延迟到期时间！'
                ];
            }
        }else{
            $msg = [
                'code'=>'0',
                'msg'=>'失败'
            ];
        }
        exit(json_encode($msg));
    }

    public function actionSwitchs(){
        $req = Yii::$app->request;
        $id = $req->post('id',0);
        if ($id){
            $user = Customer::findOne(['userid'=>$id]);
            if (time()<strtotime($user['due_time'])){
                if ($user->type==1){
                    $type = 0;
                }else if ($user->type==0){
                    $type = 1;
                }
                if ($user->code==1){
                    $code = 0;
                }else if ($user->code==0){
                    $code = 1;
                }
                $test = TestImg::find()->where(['userid'=>$id])->asArray()->one();
                $data=[
                    'user'=>$user->username,
                    'due_time'=>$user->due_time,
                    'type'=>$type,
                    'code'=>$code,
                    'img_address'=>$test['img_address'],
                    'app_address'=>$test['app_address'],
                    'ios_address'=>$test['ios_address']
                ];
                $user->type = $type;
                $user['code']= $code;
                $user->save();
                $name = 'address-'.$id;
                if(Yii::$app->cache->set($name,$data,3600*23)){
                    $msg = [
                        'code'=>'1',
                        'msg'=>'存储成功'
                    ];
                }else{
                    $msg = [
                        'code'=>'0',
                        'msg'=>'存储失败'
                    ];
                }
            }else{
                $msg = [
                    'code'=>'0',
                    'msg'=>'请延迟到期时间！'
                ];
            }
//           $res = Yii::$app->cache->get('test');
        }else{
            $msg = [
                'code'=>'0',
                'msg'=>'失败'
            ];
        }
        exit(json_encode($msg));
    }

    public function actionRenew(){
        $req = Yii::$app->request;
        if ($req->post('time',0) && $req->post('id',0)){
            $user = Customer::findOne(['userid'=>$req->post('id')]);
            $user->due_time = $req->post('time');
            if ($user->save()){
            $data=[
                'code'=>1
            ];
            }else{
                $data=[
                    'code'=>0
                ];
            }
        }else{
            $data=[
                'code'=>0
            ];
        }
        exit(json_encode($data));
    }
}
